package com.easy.controller;

import cn.hutool.extra.tokenizer.TokenizerUtil;
import com.easy.bean.User;
import com.easy.dto.LoginDTO;
import com.easy.mapper.UserMapper;
import com.easy.service.UserService;
import com.easy.util.JwtUtils;
import com.easy.util.PasswordUtils;
import com.easy.util.Result;
import com.easy.vo.LoginVO;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
//LoginController 就是提供登录接口、以及根据 Token 查询用户信息的接口
@RestController
@RequestMapping("/api/auth")
public class LoginController {

    @Autowired
    private UserService userService;
    @Autowired
    private JwtUtils jwtUtils;

    @PostMapping("/login")
    public Result login(@RequestBody LoginDTO loginDTO) {//前端传过来的 JSON（包含用户名和密码）会自动封装到 LoginDTO 里。
        System.out.println("===== 登录请求已到达控制器 =====");
        System.out.println("请求用户名：" + loginDTO.getUsername() + "，请求密码：" + loginDTO.getPassword());

        // 1. 查询用户
        User queryUser = new User();
        queryUser.setUsername(loginDTO.getUsername());
        List<User> userList = userService.all(queryUser);
        System.out.println("查询到的用户列表数量：" + (userList != null ? userList.size() : 0));

        // 2. 验证用户是否存在
        if (userList == null || userList.isEmpty()) {
            System.out.println("用户名不存在，返回错误");
            return Result.error("用户名不存在");
        }
        User user = userList.get(0);
        System.out.println("查询到的用户：" + user.getUsername() + "，数据库密码：" + user.getPassword() + " ,身份：" + user.getRole());

        // 3. 验证密码（支持明文 + BCrypt）
        boolean passwordOk = false;
        String rawPwd = loginDTO.getPassword();
        String dbPwd = user.getPassword();

      // 先尝试 BCrypt 校验
        if (PasswordUtils.matches(rawPwd, dbPwd)) {
            passwordOk = true;
        } else if (rawPwd.equals(dbPwd)) {
            // 如果数据库里存的是明文，也允许通过
            passwordOk = true;
        }

        if (!passwordOk) {
            System.out.println("密码错误，返回错误");
            return Result.error("密码错误");
        }
        System.out.println("密码验证通过");

        // 4. 生成Token
        String token = jwtUtils.generateToken(user.getUser_id(),user.getRole());
        System.out.println("生成的Token：" + token); // 关键日志：确认Token是否生成

        // 5. 构造返回数据
        LoginVO loginVO = new LoginVO();
        loginVO.setUserId(user.getUser_id());
        loginVO.setUsername(user.getUsername());
        loginVO.setRole(user.getRole());
        loginVO.setToken(token);
        System.out.println("登录成功，返回响应：" + loginVO);

        return Result.success(loginVO);

    }

    @GetMapping("/loginInfo")
    public Result loginInfo(HttpServletRequest request, HttpSession session) {
        String token = request.getHeader("authorization");//从头部获取token
        System.out.println("loginInfo:"+token);
        Integer userid = jwtUtils.getUserIdFromToken(token);
        System.out.println("userid:"+userid);
        if (userid == null) {
            throw new RuntimeException("登录异常");
        }
        User user = userService.one(userid);
        return Result.success(user);
    }


}